import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from "axios";
import qs from "qs";
import { useUserStoreHook } from "@/store/modules/user.store";
import { ResultCode } from "@/enums/common/result.enum";
import { getAccessToken } from "@/utils/auth";
import { BASE_URL } from "./url";
import { throttle } from '@/utils/index'
const messageError = throttle(() => ElMessage.error("请检查网络！"))

// 创建 axios 实例
const service = axios.create({
  baseURL: window.location.origin.includes(':5173') ? import.meta.env.VITE_APP_API_URL2 : window.location.origin, // BASE_URL
  timeout: 1000000000,
  withCredentials: true, // 跨域请求时是否需要使用凭证
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
  paramsSerializer: (params) => qs.stringify(params),
});

const whiteApi = ['/sms/test/number', '/sms/test/code']

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const accessToken = getAccessToken();
    // 如果 Authorization 设置为 no-auth，则不携带 Token
    if (config.headers.Authorization !== "no-auth" && accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    } else {
      delete config.headers.Authorization;
    }

    if(config.responseType) {
      console.log(config.responseType, 'responseType');
      
    }

    localStorage.setItem('axois url', config.url || '');

    return config;
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.headers['content-type'] == 'application/octet-stream') {
      return response.data
    }

    const { code, data, msg, message, status } = response.data;
    if (status) {
      return data;
    }

    ElMessage.error(msg || message || "系统出错");
    return Promise.reject(new Error(msg || message || "Error"));
  },
  async (error: any) => {
    // 非 2xx 状态码处理 401、403、500 等
    const response = error.response;
    if (response) {
      if(whiteApi.includes(response.config.url)) return response.data

      const { code, msg, message } = response.data;

      if (code === ResultCode.ACCESS_TOKEN_INVALID) {
        ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          const userStore = useUserStoreHook();
          userStore.clearSessionAndCache().then(() => {
            location.reload();
          });
        });
      } else {
        ElMessage.error(message || msg || "系统出错");
      }
      return Promise.reject(error.message);
    }
    messageError();
    return Promise.reject(error.message);
  }
);

export default service;
